<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
	<div class="warp">
		<div class="topBox">
			<div class="incomeBox">
				<div>今日收入</div>
				<div style="color: #ffdd57">￥{{ todayRecharge }}</div>
			</div>
			<div class="middleBox" style="margin: 16px 0;">
				<div class="middleBox-box">
					<span>累计设备</span>
					<span style="color: #ffdd57;margin-top: 16px;">{{ monthRecharge }}</span>
				</div>
				<div class="middleBox-box">
					<span>在线设备</span>
					<span style="color: #ffdd57;margin-top: 16px;">{{ totalRecharge }}</span>
				</div>
			</div>
			<div>
				<div class="minBox_notice">
					<van-notice-bar scrollable :text="systemMessage" />
				</div>
			</div>
		</div>
		<div class="minBox">
			<van-notice-bar color="#fff" background="transparent" :scrollable="false" wrapable>
				<van-swipe vertical class="notice-content" :autoplay="5000" :show-indicators="false" :touchable="false">
					<template v-if="notificationLength == 0">
						<van-swipe-item>
							<div class="flexbetween">
								<span class="minBox_top">消息通知</span>
							</div>
						<div style="height:30px;"></div>
						</van-swipe-item>
					</template>
					<template v-else>
						<van-swipe-item v-for="(item,index) in notification" :key="index" @click="swipes(item)">
							<div class="flexbetween">
								<span class="minBox_top">{{ item.title }}</span>
								<span class="hideTime">{{ item.createTime }}</span>
							</div>
							<div class="flex">
								<span style="color: red">{{ item.content }}</span>
							</div>
						</van-swipe-item>
					</template>
				</van-swipe>
			</van-notice-bar>
		</div>

		<div class="gongGe" style="margin-top: 10px;">
			<van-grid :column-num="3" :gutter="10">
				<van-grid-item v-for="item in gongGeDataList" :key="item.id" :icon="item.icon" :text="item.name"
					style="height: 6em;" @click="gridClick(item.id)">
					<i :class="item.icon" style="color: #23a6d5; font-size: 20px"></i>
					<p style="margin-bottom: 0;font-size: 13px;">{{item.name}}</p>
				</van-grid-item>
			</van-grid>
		</div>
	</div>
  </van-pull-refresh>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		useRouter
	} from 'vue-router';
	import {
		getUserid,
		getIdentity,
		setIdentity
	} from '@/utils/auth';
	import {
		notifications,
		statisticsIndex
	} from '@/api/index';
	import {
		getuserInfo
	} from '@/api/login';
	onMounted(() => {
		getnotices();//获取公告
		getstatistics();//获取统计数据
		getuserdata();//获取用户信息
	});
  // 添加 PullRefresh 组件
  import { PullRefresh as VanPullRefresh } from 'vant';
	// 公告
	const notification = ref();
	const notificationLength = ref(0);
	const systemMessage = ref();
	const getnotices = async () => {
		try {
			const userId = {
				userId: getUserid(),
			};
			const response = await notifications(userId);
			const res = response.data;
			systemMessage.value = res.systemMessage.content;
			const formattedRecords = res.notification.map(item => ({
				...item,
				// 添加格式化后的时间字段（保留原始 createTime）
				createTime: formatISODate(item.createTime)
			}));
			notification.value = formattedRecords;
			notificationLength.value = res.notification.length;
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	};
	// 统计数据
	const todayRecharge = ref(0.00);
	const totalRecharge = ref(0);
	const monthRecharge = ref(0);
	// 554223284376440832
	const getstatistics = async () => {
		try {
			const userId = {
				userId: getUserid(),
			};
			const response = await statisticsIndex(userId);
			const res = response.data;
			todayRecharge.value = Number(res.todayRecharge || 0).toFixed(2);
			totalRecharge.value = res.totalRecharge || 0;
			monthRecharge.value = res.monthRecharge || 0;
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	};
	// 获取用户信息
	const getuserdata = async () =>{
		let Identity = getIdentity()
		// 考虑Identity可能是字符串'1'的情况
		const res = Number(Identity);
		if(res !== 1){
			try {
				const userId = {
					userId: getUserid(),
				};
				const response = await getuserInfo(userId);
				setIdentity(response.data.identity)
				localStorage.setItem('userInfo', JSON.stringify(response.data)); // 用户信息保存到localStorage
			} catch (err) {
				//console.error('获取数据失败', err);
			}
		}
	};
	const router = useRouter();

	// 公告
	const swipes = (item) => {
		if (item.notificationType === 1) {
			router.push({
				path: '/settled',
			})
		}
	}

	const gongGeDataList = ref([{
			id: 1,
			icon: 'fas fa-cogs',
			name: '启动配置'
		},
		{
			id: 2,
			icon: 'fas fa-store',
			name: '商户入驻'
		},
		{
			id: 3,
			icon: 'fas fa-map-marker-alt',
			name: '投放地址'
		},
		{
			id: 4,
			icon: 'fas fa-charging-station',
			name: '流量充值'
		},
		{
			id: 5,
			icon: 'fas fa-coins',
			name: '上分记录'
		},
		{
			id: 6,
			icon: 'fas fa-users',
			name: '消费会员'
		},
		{
			id: 7,
			icon: 'fas fa-ban',
			name: '黑名单'
		},
		{
			id: 8,
			icon: 'fas fa-user-friends',
			name: '经营统计'
		},
		{
			id: 9,
			icon: 'fas fa-exchange-alt',
			name: '设备转移记录'
		},
	])
	const gridClick = (item) => {
		switch (item) {
			case 1: {
				router.push({
					path: '/bootConfiguration',
				})
				break
			}
			case 2: {
				router.push({
					path: '/settled',
				})
				break
			}
			case 3: {
				router.push({
					path: '/DeliveryAddress',
				})
				break
			}
			case 4: {
				router.push({
					path: '/dataRecharge'
				})
				break
			}
			case 5: {
				router.push({
					path: '/record',
				})
				break
			}
			case 6: {
				router.push({
					path: '/consumptionVip'
				})
				break
			}
			case 7: {
				router.push({
					path: '/blacklist'
				})
				break
			}
			case 8: {
				router.push({
					path: '/incomeInfo'
				})
				break
			}
			case 9: {
				router.push({
					path: '/transferRecord'
				})
				break
			}
		}
	}
	// 时间格式化工具函数
	const formatISODate = (isoString) => {
		// 修复格式问题：将 "+0000" 转成 "+00:00"
		if (!isoString) return "-"; // 处理空值
		try {
			const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
			const date = new Date(fixedDateString);
			// 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
			return date.toLocaleString("zh-CN", {
				year: "numeric",
				month: "2-digit",
				day: "2-digit",
				hour: "2-digit",
				minute: "2-digit",
				// second: "2-digit",
				hour12: false // 强制 24 小时制
			}).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
		} catch {
			return "-"; // 解析失败时返回占位符
		}
	};

  const refreshing = ref(false);
  const onRefresh = async () => {
    try {
      // 同时刷新所有数据
      await Promise.all([
        getnotices(),
        getstatistics(),
        getuserdata()
      ]);
    } catch (error) {
      console.error('刷新失败:', error);
    } finally {
      // 关闭刷新状态
      refreshing.value = false;
    }
  };
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		align-items: center;
	}

	.warp {
		// display: flex;
		// flex-direction: column;
		//position: relative;
		background: linear-gradient(to bottom, #23a6d5, #23d5ab);
		/* 从上到下的蓝色渐变 */
		width: 100%;
		height: 100vh;
		// position: fixed;
		overflow-y: auto;

		.topBox {
			// display: flex;
			// flex-direction: column;
			// align-items: center;
			// justify-content: center;
			width: 90%;
			margin: 0 auto;
			margin-top: 20px;
			height: 235px;
			box-sizing: border-box;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 12px;
			backdrop-filter: blur(10px);
			border: 1px solid rgba(255, 255, 255, 0.2);

			.minBox_notice {
				width: 100%;
				padding: 0 10px;
				box-sizing: border-box;
				margin-top: 24px;

				.van-notice-bar {
					//padding: 10px;
					background: rgba(255, 255, 255, 0.1);
					border-radius: 8px;
					color: white;
				}
			}

			.incomeBox {
				color: white;
				text-align: center;
				margin-top: 15px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				:nth-child(1) {
					font-size: 20px;
				}

				:nth-child(2) {
					margin-top: 10px;
					text-align: center;
					font-size: 20px;
				}
			}

			.middleBox {
				color: white;
				display: flex;
				justify-content: space-around;
				align-items: center;
				align-content: center;

				.middleBox-box {
					display: flex;
					align-items: center;
					align-content: center;
					flex-direction: column;
					// margin: 0 30px;
				}
			}
		}

		.minBox {
			width: 90%;
			margin: 10px auto;
			border: 1px solid rgba(255, 255, 255, 0.2);
			background: rgba(255, 255, 255, 0.1);
			border-radius: 12px;
			backdrop-filter: blur(10px);
			padding: 10px;
			box-sizing: border-box;
			white-space: normal;
			/* 允许换行 */
			word-break: break-all;
			/* 长单词换行 */


			.minBox_top {
				margin: 0 6px 6px 0;
				color: #ffdd57;
				font-size: 16px;
				font-weight: 700;
				flex:1;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.hideTime{
				font-size: 13px;
				max-width:125px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.notice-content {
				max-height: 75px;
				font-size: 14px;
			}
		}

		.gongGe {
			//margin-top: 5em;
			margin: 0 auto;
			width: 90%;
			// margin-left: 5px;
			// margin-right: 5px;
			border-radius: 10px;
			overflow: hidden;

			//position: absolute;
			//bottom: 70px;
			//background: #ffffff

		}
	}

	.flexbetween {
		display: flex;
		justify-content: space-between;
	}

  /* 添加下拉刷新样式 */
  .van-pull-refresh {
    height: 100vh;
    overflow: auto;
    -webkit-overflow-scrolling: touch;

    &__track {
      min-height: 100%;
    }

    &__head {
      color: #fff;
    }

    &__loading {
      .van-loading__spinner {
        color: #fff;
      }
    }
  }
</style>
<style lang="scss">
	.gongGe {

		.van-grid-item__content {
			cursor: pointer;
			border-radius: 20px;
			overflow: hidden;
			background-color: white;
			transition-duration: 0.15s;
			transition-property: box-shadow, transform, background-color;
			transition-timing-function: ease;

			p {
				font-size: 14px;
			}

			&:hover {
				background-color: #f0f0f0;
				transform: scale(1.011);
				box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
			}
		}
	}

	.minBox {
		.van-notice-bar__content.van-ellipsis {
			width: 100%;
		}

		.van-notice-bar {
			padding: 0;
			max-height: 75px;
		}

		.van-notice-bar__wrap {
			align-items: stretch;
			width: 100%;
			display: block;
		}
	}
</style>
